import { Component } from 'react';
import { Group, TextField, TextareaField, Button,Toast, Boxs,Dialog, Field } from 'saltui';

const {HBox,Box,VBox} = Boxs;
import './PageHome.less';
import DragProgressBar from '../../../components/drag-progress-bar';
import DB from '../../../app/db';
import { msgNoData } from '../../../app/variables';
const {
	Count
} = TextareaField;
const remindTimeData = [
  { value: 0, text: '不提醒' },
  { value: 1, text: '提前一天' },
  { value: 2, text: '提前两天' }
];

export default class PageHome extends Component {
  constructor(props) {
    super(props);

    //关闭加载页的遮罩效果
    $(".loading-containter").hide();
    //禁用ios弹性事件
    dd.ui.webViewBounce.disable();
    scrollTo(0, 0);
    this.state = {
      view: props.params.view,
      id: props.params.id,
      applyRecordId: props.params.applyRecordId,
      title:'',
      endTime: '',
      responseUserData: [],
      responseUserName: '',
      responseUserThird: [],
      responseUser: '',
      createdUserName:'',
      content: '',
      progress: 0,
      remindTime: remindTimeData[0],
      recordName: '',
      comDetails:"",
      isShowRemindType: false,
      isMessage:props.params.message,
      isDeleted:false,
    }

    let t = this;
    let userId = document.getElementById("userHiddenId").value;
    var isHelpNew = 1;
    dd.util.domainStorage.getItem({ //帮助按钮
       name:'meeting_helpNew_'+userId , // 存储信息的key值
       onSuccess : function(info) {
            var helpNew = info.value;
            if( typeof(helpNew) == 'undefined' || helpNew == '' ){
              isHelpNew = 2;
            }
            //初始化按钮
            t.initButton(isHelpNew);
       },
       onFail : function(err) {
            //alert(JSON.stringify(err));
       }
    });
  }

  //初始化按钮
  initButton(isHelpNew){
    //设置帮助
    /*dd.biz.navigation.setIcon({
        showIcon : true,//是否显示icon
        iconIndex : isHelpNew,//显示的iconIndex,如上图
        onSuccess : function(result) {
            location.hash='help/help_index';
        },
        onFail : function(err) {
        //jsapi调用失败将会回调此函数
        }
    });*/
  }

  componentDidMount(){
    var id = this.state.id;
    $("#App").removeAttr("style");
    var page_title = "任务详情";
    $("title").text(page_title);
    var thirdMenuType = getLoginUserInfo().thirdMenuType;
    if(thirdMenuType == 'DING'){
      dd.biz.navigation.setTitle({
          title : page_title,//控制标题文本，空字符串表示显示默认文本
          onSuccess : function(result) {},
          onFail : function(err) {}
      });
    }else if(thirdMenuType =='MH'){
      !!emp&&emp.window.setTitle({
          title: {
              text: page_title,
              icon: '',
              actionmenu: {}
          },
      });
    }

    let t = this;
    var recordId = "";
    if(t.state.view == "all"){
      recordId = this.state.applyRecordId;
    }

    var paramInfo = {taskInfoId: id, editType: "view", recordId: recordId};
    DB.SomeModuleAPI.getTaskInfo(paramInfo).then((content) => {
      let isDeleted = content.isDeleted;
      if(t.state.isMessage == 'message' && isDeleted){
        t.setState({
          isDeleted:isDeleted
        })
        return false;
      }
      var taskInfo = content.taskInfo;
      //提醒设置
      var remindType = '';
      if(taskInfo.remindType != null){
        var remindTypes = taskInfo.remindType.split(",");
        for(var i=0; i<remindTypes.length; i++){
          var type = remindTypes[i];
          var typeName = "";
          if(type == "0"){
            remindType += "短信,";
          }else if(type == "1"){
            remindType += "邮件,";
          }else if(type == "2"){
            remindType += "消息,";
          }
        }
        if(remindType != ""){
          remindType = remindType.substring(0,remindType.length-1);
        }
      }
      var isShowRemindType = true;
      if(content.noticeType == null){
        isShowRemindType = false;
      }
      t.setState({
        remindType: remindType,
        recordName: content.recordName,
        canEdit: content.canEdit,
        isResponse: content.isResponse
      });

      if(taskInfo!=undefined && taskInfo!=null){
        var endSelect = taskInfo.endTime.split(" ")[0];
        var remindTime = taskInfo.remindTime;
        var remindTimeSelect = {};
        for(var i=0; i<remindTimeData.length;i++){
          if(remindTime == remindTimeData[i].value){
            remindTimeSelect = remindTimeData[i];
          }
        }
        let createdUserName = '';
        if(content.createdUserName != null && content.createdUserName != '')
          createdUserName = content.createdUserName;
        let responseUserName = '';
        if(content.responseUserName != null && content.responseUserName != '')
          responseUserName = content.responseUserName;
        // var responseUserData = content.responseUserData;
        // var responseUserName = '';
        // var responseUserThird = [];
        // if(responseUserData != null){
        //   for(var i=0; i<responseUserData.length; i++){
        //     responseUserName += responseUserData[i].text + ",";
        //     responseUserThird.push(responseUserData[i].thirdId);
        //   }
        //   if(responseUserName != ""){
        //     responseUserName = responseUserName.substring(0, responseUserName.length-1);
        //   }
        // }
        let _content = "";
        if(taskInfo.content != null) _content = taskInfo.content;
        let _comDetails = "";
        if(taskInfo.comDetails != null) _comDetails = taskInfo.comDetails;
        t.setState({
          title: taskInfo.title,
          responseUser: taskInfo.responseUser,
          content: _content,
          progress: taskInfo.progress,
          applyRecordId: taskInfo.applyRecordId,
          comDetails: _comDetails,
          endTime: endSelect,
          remindTime: remindTimeSelect,
          responseUserName: responseUserName,
          createdUserName:createdUserName
        });
      }   
    }).catch((error) => {
    });
  }

  componentWillUnmount(){
    Dialog.hide();
  }

  changeProgress(value){
    var progress = this.state.progress;
    if(value == progress){
      return;
    }
    this.setState({
      progress: value
    });
    var param = { taskInfoId: this.state.id, progress: value };
    this.postChangeProgress(param);
  }

  postChangeProgress(param){
    let t = this;
    DB.SomeModuleAPI.changeProgress(param).then((content) => {
      Toast.show({
        type: 'success',
        content: '保存成功'
      });
      var backFlag = param.backFlag;
      if(backFlag == '1'){
        setTimeout(function(){
          backPage();
        },1000);
      }
    }).catch((error) => {
      if(typeof(error.errorMsg) == 'undefined'){
        Toast.show({
          type: 'error',
          content: '保存出错'
        });
      }else{
        Toast.show({
          type: 'error',
          content: error.errorMsg
        });
      }
    }); 
  }

  //跳转到编辑页
  editTaskInfo(){
    location.hash = "meeting/taskAdd/"+this.state.applyRecordId+"/"+this.state.id;
  }

  //发送提醒
  remindTaskInfo(){    
    /*var userArray = this.state.responseUserThird;
    dd.biz.ding.create({
      users : userArray,// 用户列表，工号
      corpId: corpid, // 企业id
      type: 1, // 附件类型 1：image  2：link
      alertType: 2, // 钉发送方式 0:电话, 1:短信, 2:应用内
      alertDate: {"format":"yyyy-MM-dd HH:mm","value":"2015-05-09 08:00"},
      attachment: {
          images: [''],
      }, // 附件信息
      text: "",  // 正文
      bizType :0, // 业务类型 0：通知DING；1：任务；2：会议；
      onSuccess : function() {
          //onSuccess将在点击发送之后调用
      },
      onFail : function() {}
    });*/
  }

  //删除任务
  deleteTaskInfo(){
    let t = this;
    Dialog.confirm({
      title: '提示',
      locale: 'zh_CN',
      content: "确定删除该任务？",
      onConfirm() {
        var param = { taskInfoId: t.state.id };
        DB.SomeModuleAPI.deleteTaskInfo(param).then((content) => {
          Toast.show({
            type: 'success',
            content: '删除成功'
          });
          setTimeout(function(){
            backPage();
          },1000);
        }).catch((error) => {
          if(typeof(error.errorMsg) == 'undefined'){
            Toast.show({
              type: 'error',
              content: '提交出错'
            });
          }else{
            Toast.show({
              type: 'error',
              content: error.errorMsg
            });
          }
        }); 
      },
      onCancel() {
        return;
      },
    });
  }

  //标记完成
  completeTaskInfo(){
    this.setState({
      progress: 100
    });
    var param = { 
      taskInfoId: this.state.id, 
      progress: 100,
      backFlag: "1"
    };
    this.postChangeProgress(param);
  }

  //保存任务反馈
  saveTaskInfo(){
    var param = { 
      taskInfoId: this.state.id, 
      comDetails: this.state.comDetails,
      type: '1',
      backFlag: '1'
    };
    this.postChangeProgress(param);
  }

  //跳转到会议详情页
  showMeeting(){
    let url ='meeting/myMeetingDetails/'+this.state.applyRecordId + '/myTask/1';
    // skip2Page(url);
    location.hash = url;
  }

  handleTextChange(field, newValue, size) {
    if (newValue.length <= size) {
      this.setState({
        [field]: newValue,
      });
    }
  }
  
  render() {
    let isDeleted = this.state.isDeleted;
    if(isDeleted){
      return (
          <div className="dd-state-page">
            <div className="dd-state-box">
              <VBox hAlign="center">
                <Box>
                  <div>
                    <img src={msgNoData} alt="" />
                  </div>
                </Box>
                <Box className="t-FS14 t-MT30 t-FAC t-LH1_3 t-FCddfontblue-40">
                内容已删除
                </Box>
              </VBox>
            </div>
          </div>
      )
    }else{
      var readOnly = true, textReadOnly = true;
      if(this.state.canEdit=='0' || this.state.isResponse=='0'){
        readOnly = false;
        textReadOnly = false;
      }

      if(this.state.view=='all' && this.state.canEdit=='0'){
        textReadOnly = true;
      }

      return (
        <div className="page-add t-PB68">
          <Group.List >
            <TextField required label="任务标题" readOnly={true} value={this.state.title}/>
          </Group.List>
          <Group.List >
            <Field layout="h" label="任务内容" multiLine>
              <Box flex={1} className="t-FAL">{this.state.content}</Box>
            </Field>
          </Group.List>
          <div>
            <Group.List>
              <Field label="进度" layout="v">
                <DragProgressBar readOnly={readOnly} progressValue={this.state.progress} onChange={(value)=>{this.changeProgress(value)}}/>
              </Field>
            </Group.List>
          </div>
          <div className="t-BCf7 t-H10"></div>
          <Group.List >
            <Field layout="h" label="任务记录" multiLine className={textReadOnly?'':'t-DN'}>
              <Box flex={1} className="t-FAL">{this.state.comDetails}</Box>
            </Field>
            <TextareaField label="任务记录" minRows={4} maxRows={7} readOnly={textReadOnly} 
              className={!textReadOnly?'':'t-DN'}
              placeholder="请输入任务记录"
              value={this.state.comDetails}
              onChange={(value) => { this.handleTextChange('comDetails', value, 200); }}>
                <Count total={200} length={this.state.comDetails.length} /></TextareaField>
          </Group.List>
          <div className="t-BCf7 t-H10"></div>
          {/* <HBox className="t-field-box t-FBAC t-BCf dd-top-border"> */}
          <Group.List >
           <TextField required label="截止日期" readOnly={true} value={this.state.endTime}/>
          </Group.List>
            {/* <div className="t-field-layout-h-label t-FS16" required>截止日期</div>
            <HBox flex="1" className="t-FBAC">
              <Box flex="1"><span className="t-FL t-FS16">{this.state.endTime}</span></Box>
            </HBox>           */}
          {/* </HBox> */}
          <Group.List>
            <HBox className="t-field-box t-FBAC">
              <div className="t-field-layout-h-label t-FS16" required> 所属会议</div>
              <HBox flex="1" className="t-FBAC">
                <Box flex="1">
                  <span className={this.state.view=="mine"?'t-FL t-FS16':'t-DN'} onClick={this.showMeeting.bind(this)}>{this.state.recordName}</span>
                  <span className={this.state.view=="all"?'t-FL t-FS16':'t-DN'}>{this.state.recordName}</span>
                </Box>
              </HBox>          
            </HBox>
          </Group.List>
          <div className="t-BCf7 t-H10"></div>
          <Group.List>
            {/*<EmployeeField required readOnly={true} label="负责人" multiple={false} 
              corpId={corpid} startWithDepartmentId={0} value={this.state.responseUserData} />*/}
            <TextField required label="负责人" readOnly={true} value={this.state.responseUserName}/>
          </Group.List>
          <Group.List>
            {/*<EmployeeField required readOnly={true} label="创建人" multiple={false} 
              corpId={corpid} startWithDepartmentId={0} value={this.state.createdUserData.label} />*/}
            <TextField required label="创建人" readOnly={true} value={this.state.createdUserName}/>
          </Group.List>
          <Group.List className={this.state.isShowRemindType ? '':'t-DN'}>
            <TextField label="到期提醒" readOnly={true} value={this.state.remindTime.text}/>
          </Group.List>
          {/*<div className={this.state.remindTime.value!=0 ? '' : 't-DN'}>
            <Group.List>
              <TextField label="提醒方式" readOnly={true} value={this.state.remindType}/>
            </Group.List>
          </div>
          <div className="t-BCf7 t-H10"></div>*/}
          <div className={this.state.view=="all"?'':'t-DN'}>
            <div className={this.state.canEdit=='0'?"":'t-DN'}>
              <Button.Group>
                <Button type="primary" display="inline" className={this.state.progress<100?'':'t-DN'} onClick={this.completeTaskInfo.bind(this)}>标记完成</Button>
                <Button type="primary" display="inline" onClick={this.editTaskInfo.bind(this)}>编辑</Button>
                {/*<Button type="secondary" display="banner" className={this.state.progress<100?'':'t-DN'} onClick={this.remindTaskInfo.bind(this)}>发送提醒</Button>*/}
                <Button type="secondary" display="inline" onClick={this.deleteTaskInfo.bind(this)}>删除</Button>
              </Button.Group>
            </div>
            <div className={(this.state.canEdit!='0' && this.state.isResponse=='0')?"":'t-DN'}>
              <Button.Group>
                <Button type="primary" className={this.state.progress<100?"":"t-DN"} display="inline" onClick={this.completeTaskInfo.bind(this)}>标记完成</Button>
                <Button type="primary" display="inline" onClick={this.saveTaskInfo.bind(this)}>保存</Button>
              </Button.Group>
            </div>
          </div>
          <div className={this.state.view=="mine"?'':'t-DN'}>
            <Button.Group>
              <Button type="primary" className={this.state.progress<100?"":"t-DN"} display="inline" onClick={this.completeTaskInfo.bind(this)}>标记完成</Button>
              <Button type="primary" display="inline" onClick={this.saveTaskInfo.bind(this)}>保存</Button>
            </Button.Group>
          </div>
        </div>
      );
    }
  }
}

